package com.example.demoproject.thread;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.demoproject.R;

public class HandlerActivity extends AppCompatActivity implements View.OnClickListener {
    Button btn;
    TextView textView;
    public static final int UPDATE_TEXT =1;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case UPDATE_TEXT:
                    textView.setText("修改了！！！");
                    break;
//                default:
//                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        btn = findViewById(R.id.changeBtn);
        textView = findViewById(R.id.handlerText);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.d("lfy","点击......");
        //以下部分在华为6.0手机上测试不执行，修改前的log可以打印出来，修改后的log不行，界面也不会改变
        //由此知道不能在子线程中修改UI界面(log都打不出来)
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Log.d("lfy","点击修改内容前......");
//                textView.setText("修改了！！！");
//                Log.d("lfy","点击修改内容后......");
//            }
//        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = UPDATE_TEXT;
                handler.handleMessage(message);
            }
        }).start();
    }
}
